---
title: "Cron, date, and mysqldump Gotcha: Escaping Percent Signs (%)"
date:  2020-05-01
category:  TechTips
---

[mysqldump](https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html) is a handy
command line utility for dumping the contents of a SQL database (or multiple
databases) to a file.  It works nicely in conjunction with
[cron](https://en.wikipedia.org/wiki/Cron) to create daily/weekly/etc. backups
of a database on a server.  If you use this combination though, there is
a gotcha that is worth knowing about: percent signs \(\%\) in a crontab will
fail.  The solution is simply to escape them with a backslash \(\\\).

One particular case in which this gotcha pops up is if you embed a *date*
command within the mysqldump command, to name the .sql backup file with the date
on which it was created.

To illustrate, here's a command to run a daily backup of a single database at
midnight each day (my\_database and my\_user are, naturally, your db and $USER
name):

`$ 0 0 * * * /usr/bin/mysqldump my_database > /home/my_user/database_backups/my_database_backup-$(date +"%F").sql`

This will create a file named: `my_database_backup-2020-05-21.sql`

The +"%F" string instructs the date command to print the output as YYYY-MM-DD,
which is nice and readable.  All of the other formatting options for date use
the same +"%{option}" sytax.

To further drive the point home: when setting up cron jobs like this, I usually
run the command manually on the command line, making sure that the command is
well-formed and that I'm getting the output that I want.  After that, I'll dump
it into a crontab.  The problem with this approach is that bash and zsh will
accept the date command with the percent sign in it, so you'll get the output
you expect.  If you just plunk the command into your crontab at this point
(*crontab -e*) and walk away, you may come back to a sad surprise if you need
to grab a backup a week or month or quarter down the line.

Happy backing-up!
